package com.ccbft.learnfile;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=findViewById(R.id.lv);
        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(i==PackageManager.PERMISSION_GRANTED){//已经授权
        }else {//没有授权就申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        Log.d(TAG, "目录是: "+externalStorageDirectory.getName());
        File[] arr = externalStorageDirectory.listFiles();
        List<MyFile> myFileList=new ArrayList<>();
        for (int j = 0; j < arr.length; j++) {
            File f=arr[j];
            String name = f.getName();
            boolean directory = f.isDirectory();
            MyFile myFile=null;
            if(directory){
                myFile=new MyFile(name,MyFile.FOLDER);
            }else {
                myFile=new MyFile(name,MyFile.FILE);
            }
            myFileList.add(myFile);
        }
        MyFileAdapter adapter=new MyFileAdapter(myFileList);
        listView.setAdapter(adapter);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==1){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, "onRequestPermissionsResult: ");
            }else {
                Log.d(TAG, "onRequestPermissionsResult: 你拒绝了授权");
            }
        }
    }
}